<?php

namespace Admin\Controller;

use Admin\Controller\CommonController;
use Usap\Service\Service;

/**
 * 后台管理通用模块
 */
class AccountController extends CommonController
{

    /*
     * 通道商列表
     * */
    public function provider_list($page = 1, $rows = 20, $sort = 'id', $order = 'asc')
    {
        //对接公司配置
        $company_config = Service::instance()->loadConfig('common', 'common', 'companyConfig');
        $provider_service = Service::instance()->find('account', 'provider');//通道商接口
        $business_service = Service::instance()->find('business', 'business');//业务指令接口
        if (IS_POST) {
            $request = I('request.');
            //获取通道商信息
            $request_data = [];
            if (!empty($request['crux'])) {
                $where['name'] = array('like', '%' . $request['crux'] . '%');
                $where['company'] = array('like', '%' . $request['crux'] . '%');
                $where['spname'] = array('like', '%' . $request['crux'] . '%');
                $where['_logic'] = 'or';
                $request_data['_complex'] = $where;
            }
            if (!empty($request['state'])) {
                if ($request['state'] == 2) {
                    $request_data['state'] = array('eq', '0');
                } elseif ($request['state'] == 1) {
                    $request_data['state'] = array('eq', '1');
                }
            }
            $provider_info = $provider_service->getInfoByCondition($request_data, $page, $rows, $sort, $order);
            $info = [];
            $count = 0;
            if (!empty($provider_info['info'])) {
                $res = [];
                $count = $provider_info['count'];
                foreach ($provider_info['info'] as $key => $value) {
                    $provider_id = $value['id'];
                    //根据通道商ID获取通道信息
                    $all_business = $business_service->getBusinessByProviderId($provider_id, 'id,business_name,state');
                    $saleid = $value['saleid'];
                    //根据商务ID获取商务昵称
                    $admin_db = D('Usap/Admin/Admin');
                    $salenanme = $admin_db->where(['userid' => $saleid])->getField('username');
                    $sms = '<a href="javascript:;" onclick="alert(\'发生错误，请先配置接口生成SMS同步地址！\')" style="text-decoration: none;color:red" title="点击复制短信同步接口">SMS</a> ';
                    $ivr = '<a href="javascript:;" onclick="alert(\'发生错误，请先配置接口生成IVR同步地址！\')" style="text-decoration: none;color:red" title="点击复制IVR同步接口">IVR</a> ';
                    $open_num = 0;//正常通道个数
                    $close_num = 0;//关闭通道个数
                    $creat_arr = explode(',', $value['create_arr']);
                    $smsparam = unserialize($value['smsparam']);
                    $ivrparam = unserialize($value['ivrparam']);
                    if (!empty($smsparam['spnumber']) && in_array('sms', $creat_arr)) {
                        $sms_url = C('API_URL') . '/Notify/' . ucfirst(strtolower($value['spname'])) . 'Sms/notice';
                        $sms = '<a href="#" onclick="prompt(\'《' . $value['name'] . '》短信接口地址\',\'' . $sms_url . '\');return false;"  title="点击复制短信同步接口" style="text-decoration: none;color: #0b96e5">SMS</a> ';
                    }
                    if (!empty($ivrparam['spnumber']) && in_array('ivr', $creat_arr)) {
                        $ivr_url = C('API_URL') . '/Notify/' . ucfirst(strtolower($value['spname'])) . 'Ivr/notice';
                        $ivr = '<a href="#" onclick="prompt(\'《' . $value['name'] . '》IVR接口地址\',\'' . $ivr_url . '\');return false;"  title="点击复制IVR同步接口" style="text-decoration: none;color: #0b96e5">IVR</a> ';
                    }
                    if (!empty($all_business)) {
                        foreach ($all_business as $k => $item) {
                            if ($item['state'] == 1) {
                                $open_num++;
                            } else {
                                $close_num++;
                            }
                        }
                    }
                    $res['provider_id'] = $value['id'];
                    $res['sp_company'] = $value['sp_company'];
                    $res['company'] = $company_config[$value['company']];
                    $res['name'] = $value['name'];
                    $res['spname'] = $value['spname'];
                    $res['salenanme'] = $salenanme;
                    $res['item'] = $open_num . ',' . $close_num;
                    $res['return_url'] = $sms . ' , ' . $ivr;
                    $res['state'] = $value['state'];
                    $info[$key] = $res;
                }
            }
            $data = array('total' => $count, 'rows' => $info);
            $this->ajaxReturn($data);
        } else {
            $menu_db = D('Usap/Admin/Menu');
            $currentpos = $menu_db->currentPos(I('get.menuid'));  //栏目位置
            $this->assign('currentpos', $currentpos);
            $this->display('provider_list');
        }
    }

    /*
     *添加通道商
     */
    public function provider_add()
    {
        //对接公司配置
        $company_config = Service::instance()->loadConfig('common', 'common', 'companyConfig');
        $admin_role_db = D('Usap/Admin/Role');
        $rolelinfo = $admin_role_db->where(array('disabled' => '0', 'rolename' => '运营分组'))->order('listorder asc')->find();
        $admin_db = D('Usap/Admin/Admin');
        //获取运营分组
        $saleid_list = $admin_db->where(['roleid' => $rolelinfo['roleid']])->getField('userid,username');
        $provider_service = Service::instance()->find('account', 'provider');//通道商接口
        $commom_service = Service::instance()->find('common', 'common');
        if (IS_POST) {
            $request = I('request.');
            //参数赋值
            $name = $request['name'];
            $spname = $request['spname'];
            $company = $request['company'];
            $sp_company = $request['sp_company'];
            $url = $request['url'];
            $username = $request['username'];
            $password = $request['password'];
            $synip = $request['synip'];
            $syn_method = $request['syn_method'];//同步类型
            $method = $request['method'];
            $dataType = $request['dataType'];
            $url_type = $request['url_type'];//地址类型
            $create_arr = $request['create_arr'];
            $smsparam = $request['smsparam'];
            $ivrparam = $request['ivrparam'];
            $sms_notify_url = $request['sms_notify_url'];
            $ivr_notify_url = $request['ivr_notify_url'];
            $saleid = $request['saleid'];
            $datetime = ("Y-m-d H:i:s");
            /*****------------条件判断-----------****/
            if (!empty($synip)) {
                $ips = explode('/', $synip);
                foreach ($ips as $ip) {
                    if ($ip && !preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $ip)) {
                        $this->error('填写IP格式错误，此项请务必谨慎填写！');
                    }
                }
            }
            $request_data = [
                'name' => $name,
                'spname' => $spname,
            ];
            $info = $provider_service->getInfoByCondition($request_data);
            if ($info['count'] > 0) {
                $this->error('通道商代号或名称与已存在');
            }
            //数据表判断
            if ($create_arr) {
                $table_arr = $commom_service->getTables(); //获取数据库表格
                foreach ($create_arr as $item) {
                    $table_name = 'syn_' . strtolower($spname) . '_' . $item;//表名
                    if (in_array($table_name, $table_arr)) {
                        $this->error('该简称表名已经存在，请重新命名');
                    }
                }
            }
            $insert_arr = array(
                'name' => $name,
                'spname' => $spname,
                'company' => $company,
                'sp_company' => $sp_company,
                'url' => $url,
                'username' => $username,
                'password' => $password,
                'synip' => $synip,
                'url_type' => $url_type,
                'syn_method' => $syn_method,
                'method' => $method,
                'dataType' => $dataType,
                'create_arr' => implode(',', $create_arr),
                'smsparam' => serialize($smsparam),
                'ivrparam' => serialize($ivrparam),
                'sms_notify_url' => $sms_notify_url ? $sms_notify_url : '未配置',
                'ivr_notify_url' => $ivr_notify_url ? $ivr_notify_url : '未配置',
                'dateline' => date('Y-m-d H:i:s', time()),
                'saleid' => $saleid ? $saleid : ''
            );
            $provider_id = $provider_service->add_provider($insert_arr);
            $num = 0;
            if ($provider_id) { //过滤获得可建表SQL
                $sql_arr = $commom_service->filterSql(strtolower($spname), $syn_method, $create_arr);
                $num = $commom_service->createTable($sql_arr);//执行SQL 建立同步表 返回执行成功个数
            }
            $message = '';
            if (!empty($create_arr)) {
                foreach ($create_arr as $item) {
                    if ($item == 'sms') {
                        $sms_conname = ucfirst(strtolower($spname)) . 'Sms';
                        $interface_name = $sms_conname . 'Controller.class.php';//接口名称
                        $interface_path = APP_PATH . 'Api/Controller/Notify/' . $interface_name;//接口路径
                        if (file_exist($interface_path)) {
                            $this->error('该简称SMS接口已经存在，请重新命名');
                        }
                        $api_file = $syn_method == 1 ? APP_PATH . 'Api/Common/Sms1Controller.class.php' : APP_PATH . 'Api/Common/Sms2Controller.class.php';
                        $sms_data = $commom_service->initReplaceField($smsparam, 1);
                        $search_arr = [];
                        $params = [];
                        if (!empty($sms_data)) {
                            $search_arr = $sms_data['search'];
                            $params = $sms_data['params'];
                        }
                        $replace_arr = array($sms_conname, $datetime, $spname, $name, $provider_id, $params['msg'], $params['mobile'], $params['spnumber'], $params['linkid'], $params['return'], $params['status'], $params['state'], $params['feecode'], $params['cpparam'], $method, $dataType);
                        $result_info = $commom_service->creatInterface($search_arr, $replace_arr, $interface_path, $api_file);
                        if ($result_info == 0) {
                            $message .= 'SMS接口创建成功';
                        } else {
                            $message .= '<font color="#ff0000">SMS接口创建失败,源不存在</font>;';
                        }
                    } else {
                        $ivr_conname = ucfirst(strtolower($spname)) . 'Ivr';
                        $interface_name = $ivr_conname . 'Controller.class.php';//接口名称
                        $interface_path = APP_PATH . 'Api/Controller/Notify/' . $interface_name;//接口路径
                        if (file_exist($interface_path)) {
                            $this->error('该简称IVR接口已经存在，请重新命名');
                        }
                        $api_file = APP_PATH . 'Api/Common/IvrController.class.php';
                        $ivrparam = $commom_service->initReplaceField($ivrparam, 2);
                        $search_arr = [];
                        $params = [];
                        if (!empty($ivrparam)) {
                            $search_arr = $ivrparam['search'];
                            $params = $ivrparam['params'];
                        }
                        $replace_arr = array($ivr_conname, $datetime, $spname, $name, $provider_id, $params['mobile'], $params['spnumber'], $params['maxtime'], $params['starttime'], $params['endtime'], $params['return'], $params['linkid'], $params['timetype'], $params['feetime'], $method, $dataType);
                        $result_info = $commom_service->creatInterface($search_arr, $replace_arr, $interface_path, $api_file);
                        if ($result_info == 0) {
                            $message .= 'IVR接口创建成功';
                        } else {
                            $message .= '<font color="#ff0000">IVR接口创建失败,源不存在</font>;';
                        }
                    }
                }
            }
            $message .= '并：创建数据表' . $num . '个';
            $data = array('code' => '0000', 'info' => $message);
            $this->ajaxReturn($data);

        } else {
            //接口参数字段配置
            $smsparam_config = Service::instance()->loadConfig('common', 'common', 'SMSApiParamConfig');
            $ivrparam_config = Service::instance()->loadConfig('common', 'common', 'IVRApiParamConfig');
            $this->assign('saleid_list', $saleid_list);
            $this->assign('company_config', $company_config);
            $this->assign('ivrparam', $ivrparam_config);
            $this->assign('smsparam', $smsparam_config);
            $this->display('provider_add');
        }
    }

    /*
    *更新通道商
    */
    public function provider_edit()
    {
        $provider_id = I('request.provider_id');
        $provider_service = Service::instance()->find('account', 'provider');
        $commom_service = Service::instance()->find('common', 'common');
        $provider_info = $provider_service->getInfoById($provider_id);
        if (empty($provider_info)) {
            $data = array('code' => '-1001', 'info' => '通道商错误',);
            $this->ajaxReturn($data);
        }
        if (IS_POST) {
            $sms = false;
            $ivr = false;
            $spname = $provider_info['spname'];
            $syn_method = $provider_info['syn_method'];
            $request = I('request.');
            $company = $request['company'];
            $sp_company = $request['sp_company'];
            $saleid = $request['saleid'];
            $url_type = $request['url_type'];
            $method = $request['method'];
            $dataType = $request['dataType'];
            if (isset($request['sms_api']) && !empty($request['sms_api'])) {
                $sms = true;
                $smsparam = $request['smsparam'];
            } else {
                $smsparam = unserialize($provider_info['smsparam']);
            }
            if (isset($request['ivr_api']) && !empty($request['ivr_api'])) {
                $ivr = true;
                $ivrparam = $request['ivrparam'];
            } else {
                $ivrparam = unserialize($provider_info['ivrparam']);
            }
            if (isset($request['create_arr']) && !empty($request['create_arr'])) {
                $create_str = $provider_info['create_arr'] . ',' . implode(',', $request['create_arr']);
            } else {
                $create_str = $provider_info['create_arr'];
            }
            $synip = $request['synip'];
            $update_arr = [
                'company' => $company,
                'sp_company' => $sp_company,
                'url_type' => $url_type,
                'method' => $method,
                'dataType' => $dataType,
                'synip' => $synip,
                'create_arr' => $create_str,
                'smsparam' => serialize($smsparam),
                'ivrparam' => serialize($ivrparam),
                'dateline' => date('Y-m-d H:i:s', time()),
                'saleid' => $saleid ? $saleid : ''
            ];
            $result = $provider_service->update_info($update_arr, $provider_id);
            $table_arr = $commom_service->getTables();//数据库表列表

            $create_arr = [];
            if ($create_str) {
                $arr = explode(',', $create_str);
                foreach ($arr as $v) {
                    $table_name = 'syn_' . strtolower($spname) . '_' . $v;
                    if (!in_array($table_name, $table_arr)) {
                        $create_arr[] = $v;
                    }
                }
            }
            $message = '';
            if ($result && !empty($create_arr)) {
                //过滤获得可建表SQL
                $sql_arr = $commom_service->filterSql($spname, $syn_method, $create_arr);
                $num = $commom_service->createTable($sql_arr);//执行SQL 建立同步表 返回执行成功个数
                $message .= '渠道商更新成功并创建数据表' . $num . '个';
            }
            $datetime = ("Y-m-d H:i:s");
            $name = $provider_info['name'];
            if ($sms) {
                if ($smsparam['spnumber']) {
                    $sms_conname = ucfirst(strtolower($spname)) . 'Sms';
                    $interface_name = $sms_conname . 'Controller.class.php';//接口名称
                    $interface_path = APP_PATH . 'Api/Controller/Notify/' . $interface_name;//接口路径
                    $api_file = $syn_method == 1 ? APP_PATH . 'Api/Common/Sms1Controller.class.php' : APP_PATH . 'Api/Common/Sms2Controller.class.php';
                    $sms_data = $commom_service->initReplaceField($smsparam, 1);
                    $search_arr = [];
                    $params = [];
                    if (!empty($sms_data)) {
                        $search_arr = $sms_data['search'];
                        $params = $sms_data['params'];
                    }
                    $replace_arr = array($sms_conname, $datetime, $spname, $name, $provider_id, $params['msg'], $params['mobile'], $params['spnumber'], $params['linkid'], $params['return'], $params['status'], $params['state'], $params['feecode'], $params['cpparam'], $method, $dataType);
                    $result_info = $commom_service->creatInterface($search_arr, $replace_arr, $interface_path, $api_file);
                    if ($result_info == 0) {
                        $message .= 'SMS更新成功';
                    } else {
                        $message .= '<font color="#ff0000">SMS接口更新失败,源文件不存在</font>;';
                    }
                }
            }
            if ($ivr) {
                if ($ivrparam['spnumber']) {
                    $ivr_conname = ucfirst(strtolower($spname)) . 'Ivr';
                    $interface_name = $ivr_conname . 'Controller.class.php';//接口名称
                    $interface_path = APP_PATH . 'Api/Controller/Notify/' . $interface_name;//接口路径
                    $api_file = APP_PATH . 'Api/Common/IvrController.class.php';
                    $ivrparam = $commom_service->initReplaceField($ivrparam, 2);
                    $search_arr = [];
                    $params = [];
                    if (!empty($ivrparam)) {
                        $search_arr = $ivrparam['search'];
                        $params = $ivrparam['params'];
                    }
                    $replace_arr = array($ivr_conname, $datetime, $spname, $name, $provider_id, $params['mobile'], $params['spnumber'], $params['maxtime'], $params['starttime'], $params['endtime'], $params['return'], $params['linkid'], $params['timetype'], $params['feetime'], $method, $dataType);
                    $result_info = $commom_service->creatInterface($search_arr, $replace_arr, $interface_path, $api_file);
                    if ($result_info == 0) {
                        $message .= 'IVR接口创建成功';
                    } else {
                        $message .= '<font color="#ff0000">IVR接口更新失败,源不存在</font>;';
                    }
                }
            }
            $data = array('code' => '0000', 'msg' => '更新成功', 'info' => $message);
            $this->ajaxReturn($data);

        } else {
            $company_config = Service::instance()->loadConfig('common', 'common', 'companyConfig');
            $admin_role_db = D('Usap/Admin/Role');
            $rolelinfo = $admin_role_db->where(array('disabled' => '0', 'rolename' => '运营分组'))->order('listorder asc')->find();
            $admin_db = D('Usap/Admin/Admin');
            //获取运营分组
            $saleid_list = $admin_db->where(['roleid' => $rolelinfo['roleid']])->getField('userid,username');
            if (!empty($provider_info['create_arr'])) {
                $provider_info['create_arr'] = explode(',', $provider_info['create_arr']);
            }
            if ($provider_id == '16') {
                $provider_info['smsparam'] = [];
                $provider_info['ivrparam'] = [];
            } else {
                if (!empty($provider_info['smsparam'])) {
                    $provider_info['smsparam'] = unserialize($provider_info['smsparam']);
                }
                if (!empty($provider_info['ivrparam'])) {
                    $provider_info['ivrparam'] = unserialize($provider_info['ivrparam']);
                }
                if ($provider_info['sms_notify_url'] == '未配置' && !empty($provider_info['smsparam']['spnumber']) && in_array('sms', $provider_info['create_arr'])) {
                    $provider_info['sms_notify_url'] = C('API_URL') . '/Notify/' . ucfirst(strtolower($provider_info['spname'])) . 'Sms/notice';
                }
                if ($provider_info['ivr_notify_url'] == '未配置' && !empty($provider_info['ivrparam']['spnumber']) && in_array('ivr', $provider_info['create_arr'])) {
                    $provider_info['ivr_notify_url'] = C('API_URL') . '/Notify/' . ucfirst(strtolower($provider_info['spname'])) . 'Ivr/notice';
                }
            }
//            dprint($provider_info);
            //接口参数字段配置
            $smsparam_config = Service::instance()->loadConfig('common', 'common', 'SMSApiParamConfig');
            $ivrparam_config = Service::instance()->loadConfig('common', 'common', 'IVRApiParamConfig');
            $this->assign('provider_info', $provider_info);
            $this->assign('ivrparam', $ivrparam_config);
            $this->assign('smsparam', $smsparam_config);
            $this->assign('saleid_list', $saleid_list);
            $this->assign('company_config', $company_config);
            $this->display('provider_edit');
        }
    }


    /**
     * 删除通道商
     */
    public function provider_delete($id)
    {
        $provider_service = Service::instance()->find('account', 'provider');
        $commom_service = Service::instance()->find('common', 'common');
        $provider_info = $provider_service->getInfoById($id);
        if (!empty($provider_info)) {


            $create_arr = explode(',', $provider_info['create_arr']);
            $result = $provider_service->delete_provider($id);
            if ($result) {
                if (in_array('sms', $create_arr)) {
                    $spname = $provider_info['spname'];
                    $table_name = 'syn_' . strtolower($spname) . '_' . 'sms';//表名
                    $sms_conname = ucfirst(strtolower($spname)) . 'Sms';
                    $interface_name = $sms_conname . 'Controller.class.php';//接口名称
                    $interface_path = APP_PATH . 'Api/Controller/Notify/' . $interface_name;//接口路径
                    $commom_service->deletTables($table_name);//删除表格
                    unlink($interface_path);//删除接口文件
                } elseif (in_array('ivr', $create_arr)) {
                    $spname = $provider_info['spname'];
                    $table_name = 'syn_' . strtolower($spname) . '_' . 'ivr';//表名
                    $sms_conname = ucfirst(strtolower($spname)) . 'Ivr';
                    $interface_name = $sms_conname . 'Controller.class.php';//接口名称
                    $interface_path = APP_PATH . 'Api/Controller/Notify/' . $interface_name;//接口路径
                    $commom_service->deletTables($table_name);
                    unlink($interface_path);
                }
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('系统错误');
        }
    }


    /****************-----------------以下是渠道信息----------------****************/


    /**
     * 渠道列表(合作方)
     */
    public function channel_list($page = 1, $rows = 20, $sort = 'channel_id', $order = 'asc')
    {
        $channel_service = Service::instance()->find('account', 'channel');
        //获取运营列表
        $admin_role_db = D('Usap/Admin/Role');
        $rolelinfo = $admin_role_db->where(array('disabled' => '0', 'rolename' => '运营人员'))->order('listorder asc')->find();
        $admin_db = D('Usap/Admin/Admin');
        //对接公司配置
        $company_config = Service::instance()->loadConfig('common', 'common', 'companyConfig');
        //获取运营人员
        $operator_list = $admin_db->where(['roleid' => $rolelinfo['roleid']])->getField('userid,username');
        //获取所有渠道名称列表
        $channel_list = $channel_service->channel_list(['state' => '1'], 'channel_id,full_name');
        if (IS_POST) {
            $request_data = [];
            if (I('request.channel_id') > 0) {
                $request_data['channel_id'] = I('request.channel_id');
            }
            if (I('request.relation_id') > 0) {
                $request_data['relation_id'] = I('request.relation_id');
            }
            if (!empty(I('request.company'))) {
                $request_data['company'] = I('request.company');
            }
//            dprint($request_data);
            $info = [];
            $channel_info = $channel_service->getInfoByCondition($request_data, $page, $rows, $sort, $order);
            if (!empty($channel_info['info'])) {
                foreach ($channel_info['info'] as $value) {
                    $userinfo = $channel_service->getAdminInfoById($value['userid']);
                    $res['channel_id'] = $value['channel_id'];
                    $res['id'] = $value['channel_id'];
                    $res['company'] = $company_config[$value['company']];
                    $res['full_name'] = $value['full_name'];
                    $res['relation_name'] = $operator_list[$value['relation_id']];
                    $res['user_name'] = $userinfo['username'];
                    if ($value['is_agreement'] == 'yes') {
                        $res['is_agreement'] = '<span style="color: green">已签</span>';
                    } else {
                        $res['is_agreement'] = '<span style="color: red">未签</span>';
                    }
                    $res['state'] = $value['state'];//渠道状态
                    $res['create_date'] = $value['create_date'];
                    if (!empty($userinfo['lastlogintime'])) {
                        $res['lastlogin'] = date('Y-m-d H:i:s', $userinfo['lastlogintime']);
                    } else {
                        $res['lastlogin'] = '未登录';
                    }
                    $info[] = $res;
                }
            }
            $data = array('total' => $channel_info['count'], 'rows' => $info);
            $this->ajaxReturn($data);
        } else {
            $menu_db = D('Usap/Admin/Menu');
            $currentpos = $menu_db->currentPos(I('get.menuid'));  //栏目位置
            $this->assign('currentpos', $currentpos);
            $this->assign('company_config', $company_config);
            $this->assign('operator_list', $operator_list);
            $this->assign('channel_list', $channel_list);
            $this->display('channel_list');
        }
    }


    /**
     * 新增渠道
     */
    public function channel_add()
    {
        //获取商务列表
        $admin_role_db = D('Usap/Admin/Role');
        $rolelinfo = $admin_role_db->where(array('disabled' => '0', 'rolename' => '运营人员'))->order('listorder asc')->find();
        $admin_db = D('Usap/Admin/Admin');
        //对接公司配置
        $company_config = Service::instance()->loadConfig('common', 'common', 'companyConfig');
        //获取运营人员
        $operator_list = $admin_db->where(['roleid' => $rolelinfo['roleid']])->getField('userid,username');

        if (IS_POST) {
            $channel_service = Service::instance()->find('Account', 'channel');
            $request = I('request.');
            if (empty($request['channel_name'])) $this->error('合作方简称不可以为空');
            if (empty($request['full_name'])) $this->error('开票公司全称不能为空');
            if (!preg_match('/^[0-9a-zA-Z]{3,16}$/', $request['username'])) $this->error('帐号名要求为3-16位英文数字组成');
            if (!preg_match('/^[0-9a-zA-Z]{6,16}$/', $request['password'])) $this->error('密码要求为6-16位英文数字组成!');
            //判断渠道用户名称是否存在
            $res = $channel_service->checkAdmin($request['username']);
            if (!$res) {
                $this->error('用户名已经存在');
            }
            $user_data = [
                'username' => $request['username'],
                'password' => md5($request['password']),
                'roleid' => 5,
                'state' => isset($request['state']) ? 1 : 0,
            ];
            //添加渠道后台账号数据
            $userid = $channel_service->addAdmin($user_data);
            //添加渠道信息
            if ($userid) {
                //渠道数据
                $channel_data = [
                    'userid' => $userid,
                    'company' => $request['company'],
                    'relation_id' => $request['relation_id'],
                    'full_name' => $request['full_name'],
                    'channel_name' => $request['channel_name'],
                    'is_agreement' => $request['is_agreement'],
                    'bank_name' => $request['bank_name'],
                    'bank_account' => $request['bank_account'],
                    'bank_number' => $request['bank_number'],
                    'sms_url' => $request['sms_url'],
                    'ivr_url' => $request['ivr_url'],
                    'mobile' => $request['mobile'],
                    'contact' => $request['contact'],
                    'state' => isset($request['state']) ? 1 : 0,
                    'create_date' => date('Y-m-d H:i:s')
                ];
                $channel_id = $channel_service->addChannel($channel_data);
                if ($channel_id) {
                    $data = array('code' => '0000', 'msg' => '添加成功', 'channel_id' => $channel_id);
                    $this->ajaxReturn($data);
                } else {
                    $channel_service->deleteAdmin($userid);
                }
            } else {
                $this->ajaxReturn(array('code' => '-0001', 'msg' => '提交数据异常，请刷新后试'));
            }
        }
        $this->assign('company_config', $company_config);
        $this->assign('operator_list', $operator_list);
        $this->display('channel_add');
    }

    /**
     * 渠道信息更新
     */
    public
    function channel_edit()
    {
        $channel_service = Service::instance()->find('Account', 'channel'); //渠道接口
        $code_service = Service::instance()->find('Code', 'code');
        //获取商务列表
        $admin_role_db = D('Usap/Admin/Role');
        $rolelinfo = $admin_role_db->where(array('disabled' => '0', 'rolename' => '运营人员'))->order('listorder asc')->find();
        $admin_db = D('Usap/Admin/Admin');
        //对接公司配置
        $company_config = Service::instance()->loadConfig('common', 'common', 'companyConfig');
        //获取运营人员
        $operator_list = $admin_db->where(['roleid' => $rolelinfo['roleid']])->getField('userid,username');

        $channel_id = I('request.channel_id');
        $channel_info = $channel_service->getInfoById($channel_id);
        $admin_info = [];
        if (!empty($channel_info)) {
            $admin_info = $channel_service->getAdminInfoById($channel_info['userid']);//获取渠道管理后台信息
        }
        $order_select = [];
        $order_list = '';
        if (IS_POST) {
            $request = I('request.');
            if (empty($request['channel_name'])) $this->error('合作方简称不可以为空');
            if (empty($request['full_name'])) $this->error('开票公司全称不能为空');
            if (!empty($request['newpassword'])) {
                if (!preg_match('/^[0-9a-zA-Z]{6,16}$/', $request['newpassword'])) $this->error('密码要求为6-16位英文数字组成!');
            }
            $user_data = [
                'userid' => $channel_info['userid'],
                'state' => isset($request['state']) ? 1 : 0,
            ];
            $password = '';
            if (!empty($request['newpassword'])) {
                $password = $request['newpassword'];
            }
            $admin_id = $channel_service->updateAdmin($user_data, $password);
            if ($admin_id !== false) {
                $channel_data = [
                    'company' => $request['company'],
                    'relation_id' => $request['relation_id'],
                    'full_name' => $request['full_name'],
                    'channel_name' => $request['channel_name'],
                    'is_agreement' => $request['is_agreement'],
                    'bank_name' => $request['bank_name'],
                    'bank_account' => $request['bank_account'],
                    'bank_number' => $request['bank_number'],
                    'sms_url' => $request['sms_url'],
                    'ivr_url' => $request['ivr_url'],
                    'mobile' => $request['mobile'],
                    'contact' => $request['contact'],
                    'state' => isset($request['state']) ? 1 : 0,
                ];
//                dprint($channel_data);
                $channel_id = $channel_service->update_info($channel_data, $channel_id);
                if ($channel_id !== false) {
                    $data = array('code' => '0000', 'msg' => '更新成功');
                    $this->ajaxReturn($data);
                }
            }
        } else {
            $this->assign('company_config', $company_config);
            $this->assign('operator_list', $operator_list);
            $this->assign('channel_info', $channel_info);
            $this->assign('user_info', $admin_info);
            $this->assign('order_list', $order_list);
            $this->display('channel_edit');
        }
    }


    /**
     * 删除渠道
     */
    public
    function channel_delete($id)
    {
        $channel_id = $id;
        $channel_service = Service::instance()->find('account', 'channel');
        $channel_info = $channel_service->getInfoById($channel_id);
        $userid = $channel_info['userid'];
        $channel_result = $channel_service->deleteChannel($channel_id);
        if (!$channel_result) {
            return $this->returnMsg('-9999');
        }
        $user_result = $channel_service->deleteAdmin($userid);
        if ($user_result) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }


    /*********------------------公共方法------------------***********/
    /**
     * 更新状态
     */
    public
    function updateState()
    {
        $type = I('request.type');
        $service = Service::instance()->find('account', $type);
        $id = I('request.id');
        $state = I('request.state');
        if ($state == 1) {
            $upstate = 0;
        } else {
            $upstate = 1;
        }
        $info = $service->getInfoById($id);
        if (!empty($info)) {
            if ($state == $info['state']) {
                $data = [
                    'state' => $upstate
                ];

                $res = $service->update_info($data, $id);
                if ($res) {
                    $data = array('code' => '0000', 'msg' => '更新成功');
                    $this->ajaxReturn($data);
                } else {
                    $data = array('code' => '0001', 'msg' => '系统错误');
                    $this->ajaxReturn($data);
                }
            }
        }

    }


    public function notify_list()
    {
        if (IS_POST) {

        } else {
            $menu_db = D('Usap/Admin/Menu');
            $currentpos = $menu_db->currentPos(I('get.menuid'));  //栏目位置
            $this->display('notify_list');
        }
    }

    public function notify_add()
    {
        if (IS_POST) {

        } else {
            $this->display('notify_add');
        }
    }

}